<?php

namespace plugin\admin\app\controller;

use app\services\OrderService;
use plugin\admin\app\controller\Base;
use plugin\admin\app\controller\Crud;
use plugin\admin\app\model\Admin;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserLevel;
use plugin\admin\app\model\UserProfile;
use plugin\admin\app\model\UserProperty;
use plugin\admin\app\model\UserTeam;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Throwable;

/**
 * 用户管理 
 */
class UserController extends Crud
{
    
    /**
     * @var User
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new User;
    }

    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);

        $contribution = $request->get('contribution');

        if (empty($request->get('id')) && (!empty($contribution[0]) && !empty($contribution[1])) ) {
             $users = UserProperty::select(['user_id'])->where('contribution', $contribution[0], $contribution[1])->get()->toArray();
             $userIds = array_column($users, 'user_id');
             if ($userIds) {
                 $where['id'] = ['in', $userIds];
             } else {
                 $where['id'] = 0;
             }
        }

        $nickname = $request->get('nickname');

        if (empty($request->get('id')) && (!empty($nickname)) ) {
            $users = UserProfile::select(['user_id'])->where('nickname', 'like', "%$nickname%")->get()->toArray();
            $userIds = array_column($users, 'user_id');
            if ($userIds) {
                $where['id'] = ['in', $userIds];
            } else {
                $where['id'] = 0;
            }
        }

        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    public function export(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);

        $limit = 99999999;

        $contribution = $request->get('contribution');

        if (empty($request->get('id')) && (!empty($contribution[0]) && !empty($contribution[1])) ) {
            $users = UserProperty::select(['user_id'])->where('contribution', $contribution[0], $contribution[1])->get()->toArray();
            $userIds = array_column($users, 'user_id');
            if ($userIds) {
                $where['id'] = ['in', $userIds];
            } else {
                $where['id'] = 0;
            }
        }

        $nickname = $request->get('nickname');

        if (empty($request->get('id')) && (!empty($nickname)) ) {
            $users = UserProfile::select(['user_id'])->where('nickname', 'like', "%$nickname%")->get()->toArray();
            $userIds = array_column($users, 'user_id');
            if ($userIds) {
                $where['id'] = ['in', $userIds];
            } else {
                $where['id'] = 0;
            }
        }

        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    /**
     * 浏览
     * @return Response
     * @throws Throwable
     */
    public function index(): Response
    {
        return raw_view('user/index', [
            'userLevels' => UserLevel::all()->pluck('name', 'id')->toArray(),
        ]);
    }

    public function children(Request $request): Response
    {
        return raw_view('user/children', [
            'parent_id' => $request->get('parent_id')
        ]);
    }

    public function relation(Request $request): Response
    {
        $level = $request->get('id');
        return raw_view('user/relation', [
            'level' => $level
        ]);
    }

    public function searchname(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $name = $request->post('name');

            $users = User::select(['id', 'nickname', 'avatar'])->where('nickname', 'like', "%{$name}%")->offset(0)->limit(20)->get()->toArray();

            $html = '<option value="">请选择</option>';

            foreach ($users as $user) {
                $html .= "<option value='{$user['id']}'><img src='{$user['avatar']}' width='50' />{$user['id']}-{$user['nickname']}</option>";
            }

            return $this->json(0, 'ok', ['html' => $html]);
        }
    }

    public function set(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $id = $request->post('id');

            User::where('id', $id)->update(['level' => $request->post('level')]);

            return $this->json(0, 'ok');
        }
    }

    public function search(Request $request): Response
    {
        $type = $request->get('type');

        $addUrl = '';
        $removeUrl = '';
        if ($type == 'coupon') {
            $addUrl = '/app/admin/coupon/add';
            $removeUrl = '/app/admin/user-coupon/remove';
        }

        return view('user/search', [
            'id' => $request->get('id'),
            'type' => $type,
            'add_api' => $addUrl,
            'remove_api' => $removeUrl,
        ]);
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException|Throwable
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return raw_view('user/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException|Throwable
     */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return raw_view('user/update');
    }

    protected function formatNormal($items, $total): Response
    {
        try {
            $userIds = array_column($items, 'id');
            $userTeams = UserTeam::whereIn('user_id', $userIds)->get()->toArray();
            $userTeams = array_combine(
                array_column($userTeams, 'user_id'),
                array_values($userTeams)
            );

            $userProperties = UserProperty::whereIn('user_id', $userIds)->get()->toArray();
            $userProperties = array_combine(
                array_column($userProperties, 'user_id'),
                array_values($userProperties)
            );

            $userProfiles = UserProfile::whereIn('user_id', $userIds)->get()->toArray();
            $userProfiles = array_combine(
                array_column($userProfiles, 'user_id'),
                array_values($userProfiles)
            );

            $parent_ids = array_column($items, 'parent_id');
            $parents = UserProfile::whereIn('user_id', $parent_ids)->get()->toArray();
            $parents = array_combine(
                array_column($parents, 'user_id'),
                array_values($parents)
            );

            $levels = UserLevel::list();
            $levels = array_combine(
                array_column($levels, 'value'),
                array_column($levels, 'name')
            );

            foreach ($items as $key=>$item) {
                $items[$key]['user_team'] = $userTeams[$item['id']];
                $items[$key]['parent_info'] = $parents[$item['parent_id']] ?? [];
                $items[$key]['user_property'] = $userProperties[$item['id']] ?? [];

                $profile = $userProfiles[$item['id']] ?? [];
                $profile['level_text'] = $levels[$item['level']];
                $items[$key]['user_profile'] = $profile;
            }

            return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
        } catch (\Exception $e) {
            echo $e->getMessage() . $e->getTraceAsString();
        }

    }
}
